package app.caihan.scframe.util

import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.NetworkUtils
import com.kunminx.architecture.ui.callback.UnPeekLiveData

/**
 * 网络状态监听管理
 * 使用lifecycle.addObserver(NetworkStateManager.instance)绑定生命周期
 *
 * @author Seven-C
 * @date 2020/7/29
 */
class NetworkStateManager : DefaultLifecycleObserver {


    val networkState = UnPeekLiveData<Boolean>()

    private val networkStatusChangedL by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {

        object : NetworkUtils.OnNetworkStatusChangedListener {
            override fun onConnected(networkType: NetworkUtils.NetworkType?) {
                //收到有网络时判断之前的值是不是没有网络，如果没有网络才提示通知 ，防止重复通知
                networkState.value?.let {
                    if (!it) {
                        //没网
                        networkState.postValue(true)
                    }
                    return
                }
                networkState.postValue(true)
                LogUtils.dTag(TAG, "networkStatusChangedL networkType.name = ${networkType?.name}")
//        Utils.getApp().toast("onConnected: ${networkType.name}")
            }

            override fun onDisconnected() {
                //收到没有网络时判断之前的值是不是有网络，如果有网络才提示通知 ，防止重复通知
                networkState.value?.let {
                    if (it) {
                        //没网
                        networkState.postValue(false)
                    }
                    return
                }
                networkState.postValue(false)
//            Utils.getApp().toast("网络不给力")
                LogUtils.dTag(TAG, "networkStatusChangedL 网络不给力")
            }
        }
    }

    override fun onResume(owner: LifecycleOwner) {
        if (!NetworkUtils.isRegisteredNetworkStatusChangedListener(networkStatusChangedL)) {
            NetworkUtils.registerNetworkStatusChangedListener(networkStatusChangedL)
        }
    }

    override fun onPause(owner: LifecycleOwner) {
        if (NetworkUtils.isRegisteredNetworkStatusChangedListener(networkStatusChangedL)) {
            NetworkUtils.unregisterNetworkStatusChangedListener(networkStatusChangedL)
        }
    }

    companion object {
        const val TAG = "NetworkStateManager"
        val instance: NetworkStateManager by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
            NetworkStateManager()
        }
    }
}